package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    // extends  ServiceImpl  当前类已经继承  ServiceImpl ，里边basemapper指向 categoryDao 无需导入
//    @Autowired
//    CategoryDao categoryDao;

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询所有商品分类并以 树形结构展示
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1、查询所有分类
        // 无查询条件，queryWrapper 参数为 null
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);

        // 2、组装成父子的树形结构

        // 2.1）、找到所有一级分类
        List<CategoryEntity> level1Menus = categoryEntityList.stream().filter(categoryEntity ->
             categoryEntity.getParentCid() == 0
        ).map(meun -> {
            meun.setChildren(getChildrens(meun, categoryEntityList));
            return meun;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());


        return level1Menus;
    }

    /**
     * 删除菜单
     *
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO：1、检查当前菜单是否被其他地方引用

        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public List<Long> getCategoryPath(Long targetCatelogId) {
        List<Long> catelogPath = new ArrayList<>();

        // 获取单个分组完整目录
        while (catelogPath.add(targetCatelogId)) {
            targetCatelogId = getById(targetCatelogId).getParentCid();
            if (targetCatelogId == 0) {
                break;
            }
        }
        // 将列表反转才可获取到 父/子/孙 的顺序
        Collections.reverse(catelogPath);

        return catelogPath;
    }

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }

    /**
     * 递归查找当前菜单的子菜单
     * @param root 当前菜单
     * @param all 所有菜单，数据源
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter((menu) -> {
            return menu.getParentCid() == root.getCatId();
        }).map((categoryEntity) -> {
            // 1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            // 2、菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}